const Router = require('koa-router');
const router = new Router();
const {db,QueryTypes } = require("../../models/db");
// 获取页面设置
// 新 科目分类取明细
router.post('/subject/getNode', async ctx => {
    let tenantId = ctx.user.tenantId;
    let fl = ctx.request.body.fl
    let code = '1'
    if(fl === '负债' ) { code = '2' }
    if(fl === '权益') { code = '4' }
    let sql = `SELECT id,name from category where tenantId=${tenantId} 
     and pid=(select id from category where tenantId=${tenantId} and typeNumber='subject' and code=${code}) and state=N'启用'  and canHasSub=1
`
    let ret = await db.query(sql, {type: QueryTypes.SELECT})

    ret.map(row =>　{
       row.label = row.name
    })

    return ctx.suc('', {list: ret});
})
// 上级分类查询下级
router.post('/subject/getNodeDetail', async ctx => {
    let tenantId = ctx.user.tenantId;
    let id = ctx.request.body.id
    let fl = ctx.request.body.fl

    let sql = `
        select id,code,name,pid,fl,state,iif(isInit=1,N'系统科目', N'自定') kmType,isnull(isInit,0) isInit,pinYin  from category where tenantId=${tenantId} and typeNumber='subject' and state=N'启用' 
    `
    if(id === 0) {
        if(fl === '资产') {
            sql += ` and code like '1%' and code <> 1 `
        }
        if(fl === '负债') {
            sql += ` and code like '2%' and code <> 2 `
        }
        if(fl === '权益') {
            sql += ` and code like '4%' and code <> 4 `
        }
    }
    else if (id === -1) {
        if(fl === '资产') {
            sql += ` and code like '1%' and code <> 1 and canHasSub=0 `
        }
        if(fl === '负债') {
            sql += ` and code like '2%' and code <> 2  and canHasSub=0`
        }
        if(fl === '权益') {
            sql += ` and code like '4%' and code <> 4 and canHasSub=0 `
        }
    }
    else {
        sql += ` and pid=${id} `
    }
    let s = `select a.*,iif(canHasSub=0,'',b.name) pidName from (${sql}) a left join category b on a.pid=b.id order by code`
    let ret = await db.query(s, {type: QueryTypes.SELECT})
    return ctx.suc('', {list: ret});
})


module.exports = router;